import subprocess

from gi.repository import Gtk
from gi.repository import GObject

from gajim.common import app
from gajim.plugins import GajimPlugin
from gajim.plugins.helpers import log_calls
from gajim.plugins.gui import GajimPluginConfigDialog

# Since Gajim 1.1.0 _() has to be imported
try:
    from gajim.common.i18n import _
except ImportError:
    pass

class FlashingLock(GajimPlugin):
    @log_calls('FlashingLock')
    def init(self):
        self.description = _('Flashing keyboard led when there are unread messages.')
        self.config_dialog = FlashingLockPluginConfigDialog(self)
        self.config_default_values = {
            'command1': ("xset led named 'Scroll Lock'", ''),
            'command2': ("xset -led named 'Scroll Lock'", ''),
            'flash': (True, ''),
            'group_cb': (True, ''),
            'group': ("Defaul group", ''),

        }
        self.contact_group_written = None
        self.is_active = None
        self.timeout = 500
        self.timeout_off = int(self.timeout / 2)
        self.id_0 = None

    def on_event_added(self, event):
        group_found = False
        if event.show_in_systray:
            # Check if event is send by user in specific group
            accounts_for_contact = app.contacts.get_accounts()
            found = False
            contact = ""
            for account in accounts_for_contact:
                if not found:
                    try:
                        contact = app.contacts.get_first_contact_from_jid(account, event.jid)
                        found = True
                    except Exception:
                        print("contact not found")
            if found:
                contact_groups = contact.groups
                for group in contact_groups:
                    if group == self.config['group']:
                    	group_found = True

        if group_found:
            self.flash_trigger(True)

    def on_event_removed(self, event_list):

        '''
         If there's an event sent by a user in specific group,
         do not stop flash trigger
         If there isn't, stop it
        '''
        remove = True
        for account in app.events.get_systray_events():
            for jid in app.events.get_systray_events()[account]:
                accounts_for_contact = app.contacts.get_accounts()
                found = False
                contact = ""
                try:
                    contact = app.contacts.get_first_contact_from_jid(account, jid)
                    found = True
                except Exception:
                    print("contact not found")
                if found:
                    contact_groups = contact.groups
                    for group in contact_groups:
                        if group == self.config['group']:
                    	    remove = False

        if remove:
            self.flash_trigger(False)

    def flash_trigger(self, activate):
        if activate:
            if self.id_0:
                return
            if self.config['flash']:
                self.id_0 = GObject.timeout_add(self.timeout, self.led_on)
            else:
                self.led_on()
                self.id_0 = True
        else:
            if self.id_0:
                if self.config['flash']:
                    GObject.source_remove(self.id_0)
                self.id_0 = None
                self.led_off()

    def led_on(self):
        subprocess.Popen('%s' % self.config['command1'], shell=True).wait()
        if self.config['flash']:
            GObject.timeout_add(self.timeout_off, self.led_off)
        return True

    def led_off(self):
        subprocess.Popen('%s' % self.config['command2'], shell=True).wait()

    @log_calls('FlashingLock')
    def activate(self):
        app.events.event_added_subscribe(self.on_event_added)
        app.events.event_removed_subscribe(self.on_event_removed)
        if app.events.get_nb_systray_events():
            if self.config['flash']:
                self.id_0 = GObject.timeout_add(self.timeout, self.led_on)
            else:
                self.led_on()
                self.id_0 = True

    @log_calls('FlashingLock')
    def deactivate(self):
        app.events.event_added_unsubscribe(self.on_event_added)
        app.events.event_removed_unsubscribe(self.on_event_removed)
        self.led_off()
        if self.id_0:
            GObject.source_remove(self.id_0)

class FlashingLockPluginConfigDialog(GajimPluginConfigDialog):
    def init(self):
        self.GTK_BUILDER_FILE_PATH = self.plugin.local_file_path(
            'config_dialog.ui')
        self.xml = Gtk.Builder()
        self.xml.set_translation_domain('gajim_plugins')
        self.xml.add_objects_from_file(self.GTK_BUILDER_FILE_PATH,
            ['config_table'])
        config_table = self.xml.get_object('config_table')
        self.get_child().pack_start(config_table, True, True, 0)
        self.xml.connect_signals(self)

    def on_run(self):
        self.isactive = self.plugin.active
        if self.plugin.active:
            app.plugin_manager.deactivate_plugin(self.plugin)
        for name in ('command1', 'command2', 'group'):
            widget = self.xml.get_object(name)
            widget.set_text(self.plugin.config[name])
        widget = self.xml.get_object('flash_cb')
        widget.set_active(not self.plugin.config['flash'])
        widget = self.xml.get_object('group_cb')
        widget.set_active(self.plugin.config['group_cb'])

    def on_close_button_clicked(self, widget):
        widget2 = self.xml.get_object('command1')
        self.plugin.config['command1'] = widget2.get_text()
        widget2 = self.xml.get_object('command2')
        self.plugin.config['command2'] = widget2.get_text()

        widget2 = self.xml.get_object('group_cb')
        self.plugin.config['group_cb'] = widget2.get_active()

        if widget2.get_active():
            widget2 = self.xml.get_object('group')
            self.plugin.config['group'] = widget2.get_text()
        widget2 = self.xml.get_object('flash_cb')
        self.plugin.config['flash'] = not widget2.get_active()
        if self.isactive:
            app.plugin_manager.activate_plugin(self.plugin)
        GajimPluginConfigDialog.on_close_button_clicked(self, widget2)
